// Modules to control application life and create native browser window
const iconv = require("iconv-lite");
// 中文编码格式，使打印中文不乱码 ,放最上方
process.stdout.write = new Proxy(process.stdout.write, {
  apply: function (func, thisArg, args) {
    if (typeof args[0] === "string") {
      args[0] = iconv.encode(args[0], "GBK"); // 或者使用适合您系统的编码
    }
    return func.apply(thisArg, args);
  },
});
const cors = require("cors");
const electron = require("electron");
const { app, BrowserWindow, shell, globalShortcut, ipcMain } = electron;
// 获取屏幕对象
const { screen: electronScreen } = electron;
const path = require("node:path");
const fs = require("fs");
const route_mysql = require("./route/route.js")
const db = require("./db/db.js");
const express = require("express");
const helmet = require("helmet");

// 热重载
require("electron-reload")(path.join(__dirname, "dist"), {
  electron: require(`${__dirname}/node_modules/electron`),
});
// 创建 Express 应用
const expressApp = express();
expressApp.use(express.static(path.join(__dirname, "dist"))); //指定静态文件目录
/**
 * 使用了 helmet 的 contentSecurityPolicy 来设置内容安全策略（CSP），从而限制应用程序与哪些源建立连接
 * 控制哪些数据源被允许访问，从而增加应用程序的安全性。
 */
expressApp.use(
  helmet.contentSecurityPolicy({
    directives: {
      connectSrc: ["'self'", "http://127.0.0.1:4000"],
    },
  })
);
// 允许所有来源，或者只允许特定来源
expressApp.use(
  cors({
    origin: "http://localhost:3001", // 允许的来源
    methods: ["GET", "POST", "PUT", "DELETE"], // 允许的 HTTP 方法
    allowedHeaders: ["Content-Type", "Authorization"], // 允许的请求头
  })
);
//创建窗口
function createWindow() {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 1800,
    height: 1000,
    icon: path.join(__dirname, "ele.ico"), // 对于 更换图标  .ico
    webPreferences: {
      preload: path.join(__dirname, "preload.js"),
      webviewTag: true, // 启用 `<webview>` 标签，允许嵌入其他网页
      nodeIntegration: false, // 启用Node.js集成，可以在渲染进程中使用Node.js API
      contextIsolation: true, // 建议开启，增加安全性
      enableRemoteModule: false, // 禁用远程模块，增强安全
    },
  });

  // 使用本地网页
  //   mainWindow.loadFile("index.html");
  //使用vue打包的网页（注意：vue打包创建路由使用history: createWebHashHistory(import.meta.env.BASE_URL)
  // mainWindow.loadFile("./dist/index.html");
  //渲染路由
  mainWindow.loadURL("http://localhost:3001/");
  // Open the DevTools.
  mainWindow.webContents.openDevTools();
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // 获取主显示器的尺寸
  const mainScreen = electronScreen.getPrimaryDisplay();
  // 获取主显示器的宽度和高度
  const { width, height } = mainScreen.size;
  createWindow();

  app.on("activate", function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
   app.on("web-contents-created", (event, contents) => {
     contents.on("new-window", (event, navigationUrl) => {
       // 在新窗口中打开链接
       event.preventDefault();
       // eslint-disable-next-line no-undef
       shell.openExternal(navigationUrl);
     });
   });

   // 使用 ipcMain 处理来自渲染进程的消息，并向渲染进程发送消息：
   ipcMain.on("send-value", (event, value) => {
     //接收渲染进程的数据
     console.log("接收渲染进程的数据send-value", value);
     //将消息写入文件(配置热重载后写入文件在项目目录内会触发热重载)
     fs.writeFileSync("../data.txt", value);
     // 回复渲染进程
     event.reply("reply-channel", value);
   });
   // 使用 ipcMain 处理来自渲染进程的异步消息
   ipcMain.handle("async-message", async (event, message) => {
     // console.log("接收渲染进程的消息async-message:", message);
     const readMessage = fs.readFileSync("../data.txt");
     console.log("主进程读取文件的数据：:", readMessage.toString());
     return readMessage.toString();
   });
   // 使用 获取mysql数据
   ipcMain.handle("getMysqlData", async (event) => {
     const readMessage = await db.getMysqlData("user", event);
     console.log(70, readMessage);
     return readMessage;
   });
});
app.on("ready", () => {
  // 注册 Ctrl+R 快捷键来刷新窗口
  globalShortcut.register("CommandOrControl+R", () => {
    const currentWindow = BrowserWindow.getFocusedWindow();
    if (currentWindow) {
      // 刷新窗口
      currentWindow.reload();
    }
  });
  // 注册 F5 快捷键来刷新窗口
  globalShortcut.register("F5", () => {
    const currentWindow = BrowserWindow.getFocusedWindow();
    if (currentWindow) {
      currentWindow.reload();
    }
  });
  // 注册 F10 快捷键来打开开发者工具
  globalShortcut.register("F10", () => {
    const currentWindow = BrowserWindow.getFocusedWindow();
    if (currentWindow) {
      // 打开开发者工具
      currentWindow.webContents.openDevTools();
    }
  });
});
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on("window-all-closed", function () {
  if (process.platform !== "darwin") app.quit();
});

// 请求路由
expressApp.use(route_mysql);

// 启动 Express 应用 发布网页
expressApp.listen(4000, () => {
  console.log("Express app is listening on port 4000!");
});
